from rest_framework.views import APIView
from rest_framework.response import Response
from utils.response import APIResponse
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated

from . import serializers, models
from libs.iPay import alipay
from utils.logging import logger


class PayAPIView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        serializer = serializers.OrderModelSerializer(data=request.data, context={'request': request})
        # 信息校验
        serializer.is_valid(raise_exception=True)
        # 订单入库
        serializer.save()
        # 返回一个支付链接
        return Response(serializer.pay_url)


class SuccessAPIView(APIView):
    def patch(self, request, *args, **kwargs):
        data = request.query_params.dict()
        sign = data.pop('sign')
        result = alipay.verify(data, sign)
        if result:
            pass
        return Response('同步回调成功')

    def post(self, request, *args, **kwargs):
        data = request.data.dict()
        sign = data.pop('sign')
        out_trade_no = data.get('out_trade_no')
        result = alipay.verify(data, sign)
        if result and data['trade_status'] in ('TRADE_SUCCESS', 'TRADE_FINISHED'):
            try:
                order = models.Order.objects.get(out_trade_no=out_trade_no)
                if order.order_status != 1:
                    order.order_status = 1
                    order.save()
                    logger.warning('%s订单完成支付' % out_trade_no)
                return Response('success')
            except:
                pass
        return Response('failed')
